/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
  public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<Integer>();
    if (root == null)
      return list;
    Deque<TreeNode> stack = new LinkedList<TreeNode>();
    TreeNode pre = null; // 记录上一个访问的结点(凭这个来判断是否访问过右子树)
    while (root != null || !stack.isEmpty()) {
      while (root != null) {
        stack.push(root);
        root = root.left;
      }
      TreeNode node = stack.peek();
      // 若右子树为空或已访问过，则弹出并记录当前节点
      if (node.right == null || pre == node.right) {
        list.add(stack.pop().val);
        pre = node;
        root = null; // 避免重复入栈左子树
      } else {
        root = node.right;
      }
    }
    return list;
  }
}